import axios from "axios";
/* 引入nprogress */
// import NProgress from "nprogress";
import { Message } from "element-ui";
// import "nprogress/nprogress.css";
import { httpUrl } from "./config";
import { getToken } from '@/utils/auth';

axios.defaults.timeout = 15000;
// Message.duration = 1000;
axios.interceptors.request.use(
  config => {
    config.baseURL = httpUrl;
    if (!config.url.includes('/login')) {
      config.headers.common['Authorization'] = 'Bearer ' +getToken();
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    const res = response.data;
    if (res.code === 200) {
      return Promise.resolve(res);
    } else if (res.code === 400) {
      Message.error(res.data);
      return Promise.reject(res)
    }
  },
  function (err) {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误(400)';
          break;
        case 401:
          err.message = '授权超时,请重新登录(401)';
          break;
        default:
          err.message =
            err.response.data.message || err.response.data.error_description;
      }
    } else {
      err.message = '连接服务器失败!';
    }
    // NProgress.done();
    Message.error(err.message);
    return Promise.reject(err.response.data);
  }
);

export default axios;
